<template>
    <div class="layout">
        <aside class="sidebar-left">
            <!-- 左侧面板内容 -->
            <!--            <el-button type="text" @click="onToggleLayer">显示</el-button>-->
            <!--            <div v-for="(layers, sceneId) in sceneLayerGroups" :key="sceneId" style="margin-bottom: 24px">-->
            <!--                <h4>场景：{{ sceneId }}</h4>-->
            <!--                <el-select-->
            <!--                    v-model="sceneVisibleMap[sceneId]"-->
            <!--                    multiple-->
            <!--                    collapse-tags-->
            <!--                    placeholder="选择要显示的图层"-->
            <!--                    @change="() => handleSceneLayerChange(sceneId)"-->
            <!--                    style="width: 300px"-->
            <!--                >-->
            <!--                    <el-option v-for="layer in layers" :key="layer.id" :label="layer.name" :value="layer.id" />-->
            <!--                </el-select>-->
            <!--            </div>-->

            <!--            <el-select v-model="selected1Layers" multiple placeholder="请选择显示的图层" @change="handleLayer1Change" style="width: 300px">-->
            <!--                <el-option v-for="layer in scene1Layers" :key="layer.id" :label="layer.name" :value="layer.name" />-->
            <!--            </el-select>-->

            <el-select v-model="selectedLayers" multiple placeholder="请选择显示的图层" @change="handleLayerChange" style="width: 300px">
                <el-option v-for="layer in scene2Layers" :key="layer.id" :label="layer.name" :value="layer.name" />
            </el-select>
        </aside>

        <main class="main-content">
            <!-- 中间内容，留空或放地图上层控件 -->
        </main>

        <aside class="sidebar-right">
            &lt;!&ndash; 右侧工具栏 &ndash;&gt;

            <!-- 属性抽屉组件 -->
            <!--            <Drawer v-model:visible="showDrawer" :data="selectedFeature" />-->
        </aside>

        <div v-if="showPopup" :style="popupStyle" class="popup-panel">
            <h4>{{ selectedFeature?.name }}</h4>
            <ul>
                <li v-for="(val, key) in selectedFeature?.properties" :key="key">
                    <strong>{{ key }}:</strong> {{ val }}
                </li>
            </ul>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import MultiSceneViewer from '@/components/MultiSceneViewer.vue';
import Drawer from '@/components/Drawer.vue';
const { __viewer } = window;

// 属性数据
// const showDrawer = ref(false);
// const selectedFeature = ref<null | {
//     name: string;
//     properties: Record<string, any>;
// }>(null);

// 定义全局或组合式响应式变量，存储每个场景的图层分组信息
const sceneLayerGroups = reactive<
    Record<
        string,
        {
            id: string;
            name: string;
            visible: boolean;
            layerObj: any;
        }[]
    >
>({});
// scene1 图层组
const scene1Layers = computed(() => sceneLayerGroups['scene1'] || []);

// 初始选中 visible 为 true 的图层
const selected1Layers = ref(scene1Layers.value.filter((l) => l.visible).map((l) => l.name));

const roomboxLayer = computed(() => {
    return sceneLayerGroups['scene1']?.find((layer) => layer.name === 'roombox');
});

// 取出 scene2 图层组
const scene2Layers = computed(() => sceneLayerGroups['scene2'] || []);

// 用于绑定 el-select 选中的图层ID数组，初始过滤出可见图层ID
const selectedLayers = ref(scene2Layers.value.filter((l) => l.visible).map((l) => l.name));

function handleLayer1Change(selectedIds: string[]) {
    scene1Layers.value.forEach((layer) => {
        const shouldShow = selectedIds.includes(layer.name);
        setLayerVisibility('scene1', layer.name, shouldShow);
    });
}

/**
 * 控制指定场景图层的显隐
 * @param sceneId 场景ID
 * @param layerId 图层ID
 * @param visible 是否显示
 */
function setLayerVisibility(sceneId: string, layerName: string, visible: boolean) {
    const group = sceneLayerGroups[sceneId];
    if (!group) return;
    const target = group.find((l) => l.name === layerName);
    if (target) {
        target.layerObj.visible = visible;
        target.visible = visible;
    }
}

/**
 * 加载指定场景URL，提取新图层，并归组存储。
 * @param sceneId 场景标识
 * @param url 场景URL地址
 */
async function openSceneWithIsolation(sceneId: string, url: string) {
    // 记录当前已有图层ID
    const beforeIds = __viewer.scene.layers._layerQueue.map((l) => l.name);
    // 异步加载新场景
    await __viewer.scene.open(url);
    // 获取加载后的全部图层
    const afterLayers = __viewer.scene.layers._layerQueue;
    // 过滤出新加载的图层
    const newLayers = afterLayers.filter((layer) => !beforeIds.includes(layer.name));
    // 将新图层转为分组数据结构
    const group = newLayers.map((layer) => ({
        id: layer.id,
        name: layer.name || `${sceneId}图层`,
        visible: layer.visible,
        layerObj: layer
    }));
    // 存入对应场景的图层组
    sceneLayerGroups[sceneId] = group;
}

/**
 * 控制指定场景所有图层显隐
 */
function setAllLayersVisibility(sceneId: string, visible: boolean) {
    const group = sceneLayerGroups[sceneId];
    if (!group) return;
    group.forEach((l) => {
        l.layerObj.visible = visible;
        l.visible = visible;
    });
}

// 监听多选变化，控制对应图层显隐
function handleLayerChange(selectedIds: string[]) {
    setLayerVisibility('scene1', roomboxLayer.value.name, false);
    // 遍历所有图层，选中的显示，没选中的隐藏
    scene2Layers.value.forEach((layer) => {
        const shouldShow = selectedIds.includes(layer.name);
        // 判断是否找到了图层
        if (selectedIds.includes(layer.name) && layer.name === 'E10F') {
            setLayerVisibility('scene1', roomboxLayer.value.name, true);
            // console.log('找到了 roombox 图层:', roomboxLayer.value.name);
        }
        setLayerVisibility('scene2', layer.name, shouldShow);
    });
    if (selectedIds.length === 0) {
        setAllLayersVisibility('scene2', true);
    }
}

// 属性信息和是否显示
const showPopup = ref(false);
const selectedFeature = ref<null | {
    name: string;
    properties: Record<string, any>;
}>(null);

// 弹窗位置
const popupX = ref(0);
const popupY = ref(0);

// 样式计算
const popupStyle = computed(() => ({
    top: `${popupY.value}px`,
    left: `${popupX.value}px`
}));

onMounted(async () => {
    // 3. 手动加载其他场景图层
    await openSceneWithIsolation(
        'scene1',
        'http://36.152.38.212:8091/iserver/services/3D-roombox/rest/realspace?token=LfYnqSHJhi0gyp-R60G6SFkIEZklK-jbeM_Vp3hOt7rGbJ47PRPNIK6LgSZf2JfO9SNVYLMPfOOhyR6oPlB17Jv6'
    );
    await openSceneWithIsolation(
        'scene2',
        'http://36.152.38.212:8091/iserver/services/3D-fxbuilding/rest/realspace?token=LfYnqSHJhi0gyp-R60G6SFkNFZknI-3ZeMzVp3hOt7rGbJ47PRPNIK6LgSZf2JfO9SNHRjzJ4ukuuYOECVbAnoTI'
    );

    const handler = new Cesium.ScreenSpaceEventHandler(__viewer.scene.canvas);
    // 模拟点击获取建筑（可替换为具体 ID 筛选）
    handler.setInputAction((movement) => {
        const pickedFeature = __viewer.scene.pick(movement.position);
        if (pickedFeature) {
            const layer = __viewer.scene.layers.getSelectedLayer();
            console.log(layer);
            console.log(layer.feature);
            // 更新属性
            selectedFeature.value = {
                name: layer.name || '未命名对象',
                properties: layer.feature ? layer.feature.properties : layer.attributes || {}
            };

            // 更新点击位置
            popupX.value = movement.position.x + 10; // +10 是为了避免挡住鼠标
            popupY.value = movement.position.y + 10;

            showPopup.value = true;
        } else {
            showPopup.value = false;
        }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
});
</script>

<style scoped>
.layout {
    position: relative;
    //z-index: 10; /* 保证高于cesium地图 */
    display: flex;
    height: 100vh;
    width: 100vw;
    //pointer-events: none; /* 先禁用鼠标事件，具体可根据需要调整 */
}

.sidebar-left {
    z-index: 2;
    pointer-events: auto; /* 激活左栏交互 */
    width: 350px;
    //background-color: rgba(255, 255, 255, 0.1);
    padding: 1rem;
}

.main-content {
    flex: 1;
    z-index: -10;
    /* 留空，地图已经挂在App.vue，或者叠加控件 */
}

.sidebar-right {
    z-index: 2;
    pointer-events: auto; /* 激活右栏交互 */
    width: 1000px;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 1rem;
}

.popup-panel {
    position: absolute;
    background: white;
    border: 1px solid #ccc;
    padding: 10px;
    min-width: 300px;
    max-width: 600px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    z-index: 9999;
}
</style>
